package com.ansion.basedb.database.sql;

import androidx.annotation.NonNull;

import java.util.ArrayList;
import java.util.List;

/**
 * created by zhaoyuntao
 * on 27/04/2023
 */
public class SQLExecutor {
    private static final List<DBTaskState> cache = new ArrayList<>();

    public static void addListener(@NonNull OnDBTaskStateChangeListener listener) {
        DBStateNotifier.getInstance().addListener(listener);
    }

    public static void removeListener(@NonNull OnDBTaskStateChangeListener listener) {
        DBStateNotifier.getInstance().removeListener(listener);
    }

    public static void execute(@NonNull DBBaseOperation<?> operation) {
        boolean dump = operation.dump();
        DBTaskState state = new DBTaskState(operation.getTag(), operation.getDbOperationCode());
        state.startWaiting();
        addCache(state);
        SQLTransactionListener listener = new SQLTransactionListener(state).setDump(dump);
        if (dump) {
            DBStateNotifier.getInstance().notifyWaiting(state);
            listener.setStatesWhenStartWaiting(dump());
        }
        operation.execute(state, listener);
        removeCache(state);
    }

    @NonNull
    private static List<DBTaskState> dump() {
        List<DBTaskState> dbStatesDump;
        synchronized (cache) {
            dbStatesDump = new ArrayList<>(cache);
        }
        return dbStatesDump;
    }

    private static void addCache(@NonNull DBTaskState dbTaskState) {
        synchronized (cache) {
            cache.add(dbTaskState);
        }
    }

    private static void removeCache(@NonNull DBTaskState dbTaskState) {
        synchronized (cache) {
            cache.remove(dbTaskState);
        }
    }
}
